// 性能监控中间件
// 监控状态管理的性能指标，提供优化建议

import { StateCreator } from 'zustand';
import { useGlobalStore } from '../globalStore';

// 性能指标接口
export interface PerformanceMetrics {
  stateUpdateCount: number;
  averageUpdateTime: number;
  maxUpdateTime: number;
  minUpdateTime: number;
  lastUpdateTime: number;
  memoryUsage: number;
  renderCount: number;
  averageRenderTime: number;
  slowUpdates: SlowUpdate[];
  hotPaths: HotPath[];
}

// 慢更新记录
export interface SlowUpdate {
  timestamp: number;
  duration: number;
  stackTrace?: string;
  stateSize: number;
  updateType: 'partial' | 'replace';
}

// 热点路径记录
export interface HotPath {
  path: string;
  count: number;
  totalTime: number;
  averageTime: number;
  lastAccess: number;
}

// 性能监控器
class PerformanceMonitor {
  private metrics: Map<string, PerformanceMetrics> = new Map();
  private slowUpdateThreshold = 16; // 16ms阈值
  private maxSlowUpdates = 50;
  private maxHotPaths = 20;

  // 初始化监控器
  initMonitor(storeName: string): void {
    if (!this.metrics.has(storeName)) {
      this.metrics.set(storeName, {
        stateUpdateCount: 0,
        averageUpdateTime: 0,
        maxUpdateTime: 0,
        minUpdateTime: Infinity,
        lastUpdateTime: 0,
        memoryUsage: 0,
        renderCount: 0,
        averageRenderTime: 0,
        slowUpdates: [],
        hotPaths: [],
      });
    }
  }

  // 记录状态更新
  recordStateUpdate(storeName: string, duration: number, stateSize: number, updateType: 'partial' | 'replace'): void {
    const metrics = this.metrics.get(storeName);
    if (!metrics) return;

    // 更新基础指标
    metrics.stateUpdateCount++;
    metrics.lastUpdateTime = duration;
    metrics.maxUpdateTime = Math.max(metrics.maxUpdateTime, duration);
    metrics.minUpdateTime = Math.min(metrics.minUpdateTime, duration);
    
    // 计算平均更新时间
    metrics.averageUpdateTime = (
      (metrics.averageUpdateTime * (metrics.stateUpdateCount - 1) + duration) / 
      metrics.stateUpdateCount
    );

    // 记录慢更新
    if (duration > this.slowUpdateThreshold) {
      const slowUpdate: SlowUpdate = {
        timestamp: Date.now(),
        duration,
        stateSize,
        updateType,
        stackTrace: this.captureStackTrace(),
      };

      metrics.slowUpdates.push(slowUpdate);
      
      // 保持慢更新记录数量限制
      if (metrics.slowUpdates.length > this.maxSlowUpdates) {
        metrics.slowUpdates.shift();
      }
    }

    // 更新内存使用情况
    this.updateMemoryUsage(storeName);
  }

  // 记录渲染性能
  recordRender(storeName: string, duration: number): void {
    const metrics = this.metrics.get(storeName);
    if (!metrics) return;

    metrics.renderCount++;
    metrics.averageRenderTime = (
      (metrics.averageRenderTime * (metrics.renderCount - 1) + duration) / 
      metrics.renderCount
    );
  }

  // 记录热点路径
  recordHotPath(storeName: string, path: string, duration: number): void {
    const metrics = this.metrics.get(storeName);
    if (!metrics) return;

    let hotPath = metrics.hotPaths.find(hp => hp.path === path);
    
    if (!hotPath) {
      hotPath = {
        path,
        count: 0,
        totalTime: 0,
        averageTime: 0,
        lastAccess: Date.now(),
      };
      metrics.hotPaths.push(hotPath);
    }

    hotPath.count++;
    hotPath.totalTime += duration;
    hotPath.averageTime = hotPath.totalTime / hotPath.count;
    hotPath.lastAccess = Date.now();

    // 按访问频率排序并保持数量限制
    metrics.hotPaths.sort((a, b) => b.count - a.count);
    if (metrics.hotPaths.length > this.maxHotPaths) {
      metrics.hotPaths = metrics.hotPaths.slice(0, this.maxHotPaths);
    }
  }

  // 获取性能指标
  getMetrics(storeName: string): PerformanceMetrics | null {
    return this.metrics.get(storeName) || null;
  }

  // 获取所有性能指标
  getAllMetrics(): Map<string, PerformanceMetrics> {
    return new Map(this.metrics);
  }

  // 重置指标
  resetMetrics(storeName?: string): void {
    if (storeName) {
      this.metrics.delete(storeName);
    } else {
      this.metrics.clear();
    }
  }

  // 生成性能报告
  generateReport(storeName?: string): string {
    const stores = storeName ? [storeName] : Array.from(this.metrics.keys());
    let report = '# 性能监控报告\n\n';

    for (const store of stores) {
      const metrics = this.metrics.get(store);
      if (!metrics) continue;

      report += `## Store: ${store}\n\n`;
      report += `- 状态更新次数: ${metrics.stateUpdateCount}\n`;
      report += `- 平均更新时间: ${metrics.averageUpdateTime.toFixed(2)}ms\n`;
      report += `- 最大更新时间: ${metrics.maxUpdateTime.toFixed(2)}ms\n`;
      report += `- 最小更新时间: ${metrics.minUpdateTime === Infinity ? 'N/A' : metrics.minUpdateTime.toFixed(2)}ms\n`;
      report += `- 内存使用: ${(metrics.memoryUsage / 1024 / 1024).toFixed(2)}MB\n`;
      report += `- 渲染次数: ${metrics.renderCount}\n`;
      report += `- 平均渲染时间: ${metrics.averageRenderTime.toFixed(2)}ms\n`;
      
      if (metrics.slowUpdates.length > 0) {
        report += `\n### 慢更新记录 (>${this.slowUpdateThreshold}ms)\n`;
        metrics.slowUpdates.slice(-5).forEach((update, index) => {
          report += `${index + 1}. ${update.duration.toFixed(2)}ms (${new Date(update.timestamp).toLocaleTimeString()})\n`;
        });
      }

      if (metrics.hotPaths.length > 0) {
        report += `\n### 热点路径\n`;
        metrics.hotPaths.slice(0, 5).forEach((hotPath, index) => {
          report += `${index + 1}. ${hotPath.path}: ${hotPath.count}次, 平均${hotPath.averageTime.toFixed(2)}ms\n`;
        });
      }

      report += '\n';
    }

    return report;
  }

  // 获取优化建议
  getOptimizationSuggestions(storeName: string): string[] {
    const metrics = this.metrics.get(storeName);
    if (!metrics) return [];

    const suggestions: string[] = [];

    // 检查慢更新
    if (metrics.slowUpdates.length > 5) {
      suggestions.push('检测到多次慢更新，考虑优化状态结构或使用批量更新');
    }

    // 检查平均更新时间
    if (metrics.averageUpdateTime > 10) {
      suggestions.push('平均更新时间较长，考虑使用状态分割或选择器优化');
    }

    // 检查内存使用
    if (metrics.memoryUsage > 50 * 1024 * 1024) { // 50MB
      suggestions.push('内存使用较高，考虑清理不必要的状态或实现状态清理机制');
    }

    // 检查热点路径
    const topHotPath = metrics.hotPaths[0];
    if (topHotPath && topHotPath.count > 100 && topHotPath.averageTime > 5) {
      suggestions.push(`热点路径 "${topHotPath.path}" 访问频繁且耗时，考虑缓存或优化`);
    }

    return suggestions;
  }

  // 捕获堆栈跟踪
  private captureStackTrace(): string {
    try {
      throw new Error();
    } catch (error) {
      return (error as Error).stack || '';
    }
  }

  // 更新内存使用情况
  private updateMemoryUsage(storeName: string): void {
    if (typeof performance !== 'undefined' && (performance as any).memory) {
      const metrics = this.metrics.get(storeName);
      if (metrics) {
        metrics.memoryUsage = (performance as any).memory.usedJSHeapSize;
      }
    }
  }
}

// 全局性能监控器实例
export const performanceMonitor = new PerformanceMonitor();

// 性能监控中间件
export const withPerformanceMonitoring = <T>(
  storeCreator: StateCreator<T, [], [], T>,
  storeName: string
): StateCreator<T, [], [], T> => {
  return (set, get, store) => {
    // 初始化监控器
    performanceMonitor.initMonitor(storeName);

    // 包装set函数
    const wrappedSet = (partial: any, replace?: boolean) => {
      const startTime = performance.now();
      const prevState = get();
      
      set(partial, replace);
      
      const endTime = performance.now();
      const duration = endTime - startTime;
      const newState = get();
      
      // 计算状态大小（简化版本）
      const stateSize = JSON.stringify(newState).length;
      
      // 记录性能指标
      performanceMonitor.recordStateUpdate(
        storeName,
        duration,
        stateSize,
        replace ? 'replace' : 'partial'
      );

      // 如果启用了全局性能监控，更新全局指标
      const globalStore = useGlobalStore.getState();
      if (globalStore.settings.performanceMonitor) {
        globalStore.updatePerformanceMetrics({
          memoryUsage: (performance as any).memory?.usedJSHeapSize || 0,
          renderTime: duration,
        });
      }
    };

    return storeCreator(wrappedSet, get, store);
  };
};

// React Hook for performance monitoring
export const usePerformanceMonitoring = (storeName: string) => {
  const [metrics, setMetrics] = React.useState<PerformanceMetrics | null>(null);
  const [suggestions, setSuggestions] = React.useState<string[]>([]);

  React.useEffect(() => {
    const updateMetrics = () => {
      const currentMetrics = performanceMonitor.getMetrics(storeName);
      setMetrics(currentMetrics);

      if (currentMetrics) {
        setSuggestions(performanceMonitor.getOptimizationSuggestions(storeName));
      }
    };

    // 初始更新
    updateMetrics();

    // 定期更新指标
    const interval = setInterval(updateMetrics, 5000); // 每5秒更新一次

    return () => clearInterval(interval);
  }, [storeName]);

  return {
    metrics,
    suggestions,
    generateReport: () => performanceMonitor.generateReport(storeName),
    resetMetrics: () => performanceMonitor.resetMetrics(storeName),
  };
};

// 导出性能监控器和相关工具
export { PerformanceMonitor };
export type { PerformanceMetrics, SlowUpdate, HotPath };
